package com.cloudwave.trailends.service;

import java.util.Timer;
import java.util.TimerTask;

import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.os.SystemClock;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.mapapi.model.LatLng;
import com.cloudwave.trailends.AppContext;
import com.cloudwave.trailends.Constants;
import com.cloudwave.trailends.R;
import com.cloudwave.trailends.domain.LinePoint;
import com.cloudwave.trailends.domain.RidingLine;
import com.cloudwave.trailends.domain.User;
import com.cloudwave.trailends.ui.MainActivity;
import com.cloudwave.trailends.utils.CalculateUtils;
import com.cloudwave.trailends.utils.DateUtils;
import com.cloudwave.trailends.utils.StatisticsUtils;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.db.table.DbModel;
import com.lidroid.xutils.exception.DbException;

/**
 * 骑行后台服务
 * 
 * @author 龙雪
 * @email 569141948@qq.com
 * @date 2014-4-21
 * @time 下午10:49:21
 */

public class RidingService extends Service {
	private static final String TAG = "RidingService";
	public static final int NOTIF_RIDING = 100;
	
	public static final String RIDING_SERVICE = "com.cloudwave.trailends.RidingService";
	
	public static final String RIDING_TIMER = "riding_timer";
	
	public static long now_rlId = 0;
	
	private RidingLine tNow = null;
	
	private float totalMileage = 0.00f;  //总距离
	private int totalPoint = 0;  //坐标点总数
	private long totalTime = 0;  //时长
	private long totalValidTime = 0;  //有效时长
	private double distance = 0;  //增量
	private float totalClimb = 0;  //总爬升
	private float totaDecline = 0;  //总下降
	
//	private int stopTimes = 0;
	
	private double lastLongitude = 0.00f;
	private double lastLatitude = 0.00f;
	private double lastDirection = 0.00f;
	private double lastAltitude = 0.00f;
	private long lastTime = 0l;
	
	//定位相关
    private LocationClient locClient;
  	private MyLocationListenner myListener;
  	
  	private NotificationManager notificationManager; 
	private Notification notification;
	private NotificationCompat.Builder builder;
	
	
	
	public static final String LOCATION_STAT = "location_stat";
	
//	public static final String UPDATE_TOTAL = "te_update_total";
	public static final String UPDATE_STAT = "te_update_stat";
	public static final String UPDATE_LOCATION = "te_update_location";
	public static final String UPDATE_VALID_LOCATION = "te_update_valid_location";
	public static final String UPDATE_SPEED = "te_update_speed";
//	public static final String UPDATE_DISTANCE = "te_update_distance";
	public static final String UPDATE_PAUSE = "te_update_pause";
//	public static final String UPDATE_TIME = "te_update_time";
	
	public static final String RL_UPDATE = "rl_update";
	
//	public static final int CTRL_START = 1;
//	public static final int CTRL_PAUSE = 2;
//	public static final int CTRL_STOP = 3;
	
	public static final String CTRL_START = "ctrl_start";
	public static final String CTRL_PAUSE = "ctrl_pause";
	public static final String CTRL_STOP = "ctrl_stop";
	public static final String CTRL_CONTINUE = "ctrl_continue";
	
	public static final String SYS_EXIT = "sys_exit";
	
	public static final int SERVICE_EXIT = 0;
	
	private Timer mTimer = null;
	private TimerTask mTimerTask = null;
//	private Handler mHandler = null;
	private static int delay = 1000;  //1s
	private static int period = 1000;  //1s
//	private static final int MSG_TIMMER = 100;
	
	private CrtlReceiver crtlReceiver;
	private AlarmReceiver alarmReceiver;
	
	private DbUtils dbu = null;
			
//	private boolean isFirstLoc = true;
	private boolean isRuning = false;
	private int ridingStatus = 0;  //0:未启动;1:运动中;3:暂停;4:停止
//	private boolean isFirstLoc = true;
	
//	private DecimalFormat df = new DecimalFormat("#0.00");
	
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
	
	@Override
	public void onCreate() {
		super.onCreate();
		Log.i(TAG, "onCreate!");
		// 声明一个通知，并对其进行属性设置

//		builder = new NotificationCompat.Builder(
//				RidingService.this).setSmallIcon(R.drawable.notice_ico)
//				.setContentTitle("车轮不息")
//				.setContentText("未开始...");
//		
//		// 声明一个Intent，用于设置点击通知后开启的Activity
//		Intent resuliIntent = new Intent(RidingService.this, MainActivity.class);
//		resuliIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);  //销毁当前栈中的其他所有activity
//		PendingIntent resultPendingIntent = PendingIntent.getActivity(RidingService.this, 0, resuliIntent, PendingIntent.FLAG_CANCEL_CURRENT);
//		builder.setContentIntent(resultPendingIntent);
//		notification = builder.build();
//		
//		notificationManager = (NotificationManager) getSystemService(android.content.Context.NOTIFICATION_SERVICE);
		
		//自定义通知栏视图
		RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.notice_riding_service);
		contentView.setTextViewText(R.id.tvRidingNoticeTitle, "车轮不息");
		contentView.setTextViewText(R.id.tvRidingNoticeStatus, "未开始...");
		
		//定义点击通知小时时的动作
		Intent resuliIntent = new Intent(RidingService.this, MainActivity.class);
		resuliIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);  //销毁当前栈中的其他所有activity
		PendingIntent resultPendingIntent = PendingIntent.getActivity(RidingService.this, 0, resuliIntent, PendingIntent.FLAG_CANCEL_CURRENT);
		
		//设置通知消息属性
		builder = new NotificationCompat.Builder(RidingService.this)
			.setOngoing(true)
			.setSmallIcon(R.drawable.notice_ico)
			.setContentTitle("车轮不息")
			.setContent(contentView)
			.setContentIntent(resultPendingIntent)
			.setTicker("车轮不息已准备就绪!");
		
		//创建通知消息
		notification = builder.build();
		
		notificationManager = (NotificationManager) getSystemService(android.content.Context.NOTIFICATION_SERVICE);
				
		// 把当前服务设定为前台服务，并指定显示的通知。
		startForeground(NOTIF_RIDING, notification);
		
		registerReceiver();
		
		initLocator();
		
		initDb();
		
		initRidingLine();
		
		initTimer();
	}
	
	private void reset(int status) {
		
		if (tNow != null && tNow.getId() != null) {
			updateTrip(tNow, null, null);
		}
		
		totalMileage = 0f;
		totalPoint = 0;
		totalTime = 0;
		totalValidTime = 0;
		distance = 0d;
		
		totalClimb = 0;  //总爬升
		totaDecline = 0;  //总下降
		
		lastLongitude = 0.00f;
		lastLatitude = 0.00f;
		lastDirection = 0.00f;
		lastAltitude = 0.00f;
		lastTime = 0l;
		
		if (tNow != null && tNow.getId() != null) {
			endTrip(tNow);
		}
		
		if ( tNow == null && status != 0 ) {
			initRidingLine();
		}
		
		if ( locClient.isStarted() ) {
			locClient.stop();
		}
	}
	
	private void initLocator() {
		if (locClient != null && locClient.isStarted()) {
    		return ;
    	}
    	
//		locClient = new LocationClient(getApplicationContext());
		locClient = ((AppContext) getApplication()).getLocationClient();
//		locClient = AppContext.getInstance().getLocationClient();
        myListener = new MyLocationListenner();
        locClient.registerLocationListener(myListener);
        locClient.setLocOption(AppContext.getLocClientOption());
	}
	
	private void initDb() {
		if ( dbu == null ) {
			dbu = DbUtils.create(this.getApplicationContext(), Constants.DB_NAME);
		}
	}
	
	private void initRidingLine() {
		if (tNow == null) {
			try {
				String today = DateUtils.nowDate();
//				DbModel dbModel = dbu.findDbModelFirst(Selector.from(RidingLine.class)
//						.select("id_,max(times_) as times_,count(1) as count_")
//						.where("DATE(startTime_)", "==", today));
				
				RidingLine rlTmp = dbu.findFirst(Selector.from(RidingLine.class).orderBy("timestamp_", true).orderBy("times_", true));
				if (rlTmp == null 
						|| DateUtils.compareDate(rlTmp.getStartTime(), DateUtils.now()) != 0 ) {
					tNow = new RidingLine();
					tNow.setTitle(today+"-["+1+"]");
					tNow.setTimestamp(DateUtils.nowTimestamp());
					tNow.setTimes(1);
					tNow.setIsNow(true);
					tNow.setCrudStatus(RidingLine.CRUD_STATUS_ADD);
				} else {
					int times = rlTmp.getTimes();
					tNow = new RidingLine();
					tNow.setTitle(today+"-["+String.valueOf(times+1)+"]");
					tNow.setTimestamp(DateUtils.nowTimestamp());
					tNow.setTimes(times+1);
					tNow.setIsNow(true);
					tNow.setCrudStatus(RidingLine.CRUD_STATUS_ADD);
				}
				if ( ((AppContext) getApplication()).isLogin() ) {
					User sessionUser = ((AppContext) getApplication()).loadLoginUser();
					tNow.setCreator(sessionUser);
//					UserInfo userInfo = ((AppContext) getApplication()).loadLoginUserInfo();
					tNow.setUserWeight(sessionUser.getWeight());
				}
				String model = StatisticsUtils.newInstance(this).getModel();
				tNow.setModel(model);
			} catch (DbException e) {
				Toast.makeText(RidingService.this, "查询当前骑记失败~_~", Toast.LENGTH_SHORT).show();
				Log.e(TAG, e.getMessage());
			}
		}
	}
	
	private void initTimer() {
		Intent intent = new Intent();
	    intent.setAction(RIDING_TIMER);
	    PendingIntent sender = PendingIntent.getBroadcast(RidingService.this, 0, intent, 0);
	    
	    final AlarmManager am = (AlarmManager) this.getSystemService(ALARM_SERVICE);
		am.setRepeating(AlarmManager.RTC_WAKEUP, SystemClock.elapsedRealtime(), 1*1000, sender);
	}
	
	private void startTrip() {
		
		if ( tNow == null ) {
			initRidingLine();
		}
		
		try {
			tNow.setIsNow(true);
			tNow.setTotalMileage(0f);
			tNow.setTotalPoint(0);
			tNow.setTotalTime(0);
			tNow.setTotalValidTime(0);
			tNow.setStartTime(DateUtils.now());
			if ( !((AppContext) getApplication()).isLogin() ) {
				tNow.setCreator(((AppContext) getApplication()).loadLoginUser());
			}
			
			dbu.saveBindingId(tNow);
			
			now_rlId = tNow.getId();
		} catch (DbException e) {
			Toast.makeText(RidingService.this, "开始骑行记录失败~_~", Toast.LENGTH_SHORT).show();
			Log.e(TAG, e.getMessage());
		}
	}
	
	public class MyLocationListenner implements BDLocationListener {
    	
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location == null || location.getLatitude() == 0 || location.getLongitude() == 0 )
                return ;
            Log.i(TAG, "获取到定位数据!");
            Log.i(TAG, "纬度:"+location.getLatitude());
            Log.i(TAG, "经度:"+location.getLongitude());
            
        	Log.i(TAG, "上次纬度:"+lastLatitude);
            Log.i(TAG, "上次经度:"+lastLongitude);
            
            int locType = location.getLocType();
            Log.i(TAG, "locType:"+locType);
            
            if ( locType >= 162 ) {
            	notification.contentView.setTextViewText(R.id.tvRidingNoticeStatus, "定位失败~_~");
    			notificationManager.notify(NOTIF_RIDING, notification);
    			Toast.makeText(RidingService.this, "位失败~_~", Toast.LENGTH_SHORT).show();
            	Log.e(TAG, "定位失败~_~");
            	return ;
            }
            
            if (locType != BDLocation.TypeGpsLocation) {
            	Log.i(TAG, "舍弃不是GPS的地点!");
            	// 舍弃不是GPS坐标，但是为了首次定位
            	Intent intent = new Intent();
     			intent.setAction(UPDATE_LOCATION);
     			intent.putExtra("latitude", location.getLatitude());
     			intent.putExtra("longitude", location.getLongitude());
     			intent.putExtra("direction", location.getDirection());
     			intent.putExtra("radius", location.getRadius());
     			
     			sendBroadcast(intent); // 给SimpleActivity发送广播
     			
            	return ;
            }
			
//			if ( isFirstLoc ) {
//				notification.defaults = Notification.DEFAULT_SOUND;
//			} else {
//				
//			}
			notification.contentView.setTextViewText(R.id.tvRidingNoticeStatus, "定位成功");
			notificationManager.notify(NOTIF_RIDING, notification);
			
//			Intent intentLoc = new Intent();
//			intentLoc.setAction(LOCATION_STAT);
//			intentLoc.putExtra("locationStat", 2);
// 			sendBroadcast(intentLoc);
 			
            //对于通知的发送频率,是应该放在定时器里面呢,还是应该放在这个监听事件里面呢？###
            if ( lastLatitude == 0 && lastLongitude == 0 ) {  //更新计时
            	Log.i(TAG, "首次定位, 或者根本就没移动!");
            	lastLatitude = location.getLatitude();
            	lastLongitude = location.getLongitude();
            	lastDirection = location.getDirection();
            	
            	Intent intent = new Intent();
     			intent.setAction(UPDATE_LOCATION);
            	intent.putExtra("latitude", lastLatitude);
     			intent.putExtra("longitude", lastLongitude);
     			intent.putExtra("direction", lastDirection);
     			intent.putExtra("radius", location.getRadius());
     			sendBroadcast(intent);
     			
     			ridingStatus = 3;
     			return ;
            }
            
//        	distance = DistanceUtil.getDistance(ll1, ll2);
//        	if (distance == -1) {
//        		Log.i(TAG, "计算坐标间的距离转换错误");
//        	}
            
            Intent intentSpeed = new Intent();
            intentSpeed.setAction(UPDATE_SPEED);
            intentSpeed.putExtra("now_rlId", tNow.getId());
            intentSpeed.putExtra("speed", location.getSpeed());
 			
 			float maxSpeed = 0;
 			if ( tNow != null && tNow.getMaxSpeed() != null) {
 				maxSpeed = tNow.getMaxSpeed();
 			}
 			intentSpeed.putExtra("maxSpeed", maxSpeed);
 			float avgSpeed = 0;
 			if ( tNow != null && tNow.getMaxGpsSpeed() != null) {
 				avgSpeed = tNow.getAvgSpeed();
 			}
 			intentSpeed.putExtra("avgSpeed", avgSpeed);
 			float maxGpsSpeed = 0;
 			if ( tNow != null && tNow.getMaxGpsSpeed() != null) {
 				maxGpsSpeed = tNow.getMaxGpsSpeed();
 			}
 			intentSpeed.putExtra("maxGpsSpeed", maxGpsSpeed);
 			
 			
 			
            LatLng ll1 = new LatLng(location.getLatitude(), location.getLongitude());
        	LatLng ll2 = new LatLng(lastLatitude, lastLongitude);
            distance = CalculateUtils.getShortDistance(ll1.longitude, ll1.latitude
        			, ll2.longitude, ll2.latitude);
            Log.i(TAG, "间距:"+distance);
        	if ( distance < 5 || location.getSpeed() <= 0 ) {
        		Log.i(TAG, "位置停留!");
        		
        		distance = 0;
        		
        		Intent intent = new Intent();
        		intent.setAction(UPDATE_PAUSE);
        		intent.putExtra("distance", distance);
        		sendBroadcast(intent);
        		
				notification.contentView.setTextViewText(R.id.tvRidingNoticeStatus, "暂停中...");
				notificationManager.notify(NOTIF_RIDING, notification);
				
				ridingStatus = 3;
				
				intentSpeed.putExtra("speed", 0);
				sendBroadcast(intentSpeed);
				return ;
        	} else {
        		sendBroadcast(intentSpeed);
        	}
        	
        	ridingStatus = 1;
        	
			notification.contentView.setTextViewText(R.id.tvRidingNoticeStatus, "行进中...");
			notificationManager.notify(NOTIF_RIDING, notification);
			
        	totalPoint ++;
        	totalMileage += distance;
        	
        	if (totalMileage > (Constants.MAX_MILEAGE * 1000)) {
    			
    			notification.contentView.setTextViewText(R.id.tvRidingNoticeStatus, "对不起您的骑行能力超出我我们的想象...");
    			notificationManager.notify(NOTIF_RIDING, notification);
    			
    			ridingStatus = 3;
    			//这里要发送一个最大值的通知###
    			return ;
        	}
        	
        	ridingStatus = 2;
        	
        	Intent intent = new Intent();
 			intent.setAction(UPDATE_STAT);
 			intent.putExtra("now_rlId", tNow.getId());
 			intent.putExtra("totalMileage", totalMileage);
 			intent.putExtra("distance", (int) distance);
 			intent.putExtra("totalPoint", totalPoint);
 			intent.putExtra("totalTime", totalTime);
 			intent.putExtra("totalValidTime", totalValidTime);
 			sendBroadcast(intent);
 			
 			Intent intentValidLocation = new Intent();  //给地图浏览页面发通知
 			intentValidLocation.setAction(UPDATE_VALID_LOCATION);
 			intentValidLocation.putExtra("latitude", lastLatitude);
 			intentValidLocation.putExtra("longitude", lastLongitude);
 			sendBroadcast(intent);
 			
 			//计算阶段速度以记录最大速度
        	long time = totalTime - lastTime;
        	float speed = (float) ((distance / (float) 1000) / ((float) time / (float) 60 / (float) 60));
        	
        	//计算爬升和下降
        	double diffAltitude = location.getAltitude() - lastAltitude;
        	if ( diffAltitude > 0 ) {
        		totalClimb += diffAltitude;
        	} else {
        		totaDecline += diffAltitude;
        	}
        	
        	LinePoint loc = new LinePoint();
			loc.parseBDLocation(location, locClient.getVersion(), locClient.getLocOption().getCoorType(), location.getLocType());
			loc.setDistance(totalMileage);
			loc.setCreateTime(DateUtils.now());
			loc.setTimestamp(DateUtils.nowTimestamp());
			
			updateTrip(tNow, loc, speed);
			
			saveLoc(loc, tNow);
			
			lastTime = totalTime;
			lastLatitude = location.getLatitude();
        	lastLongitude = location.getLongitude();
        	lastDirection = location.getDirection();
        	lastAltitude = location.getAltitude();
        }
        
        public void onReceivePoi(BDLocation poiLocation) {
            if (poiLocation == null){
                return ;
            }
        }
    }
	
	private void saveLoc(LinePoint loc, RidingLine t) {
		Log.v(TAG, "---保存地理位置---");
		loc.setRidingLine(t);
		loc.setCreatorId(((AppContext) getApplication()).getUid());
		try {
			dbu.save(loc);
		} catch (DbException e) {
			Toast.makeText(RidingService.this, "保存位置数据失败~_~", Toast.LENGTH_SHORT).show();
			Log.e(TAG, e.getMessage());
		}
	}
	
	private void updateTrip(RidingLine t, LinePoint loc, Float speed) {
//		Toast.makeText(this, "计算出来的速度:"+speed, Toast.LENGTH_SHORT).show();
		float avgSpeed = (totalMileage / 1000) / (totalTime / (60 * 60));
		
		try {
			t.setTotalMileage(totalMileage);
			t.setTotalPoint(totalPoint);
			t.setTotalTime(totalTime);
			t.setTotalClimb(totalClimb);
        	t.setTotaDecline(totaDecline);
			t.setTotalValidTime(totalValidTime);
			t.setAvgSpeed(avgSpeed);  //###这里应该保留两位小数，还是在显示的时候保留两位小数呢？
//			t.setIsNow(true);
			
			dbu.update(t, "totalMileage_","totalPoint_","totalTime_","totalClimb_","totaDecline_","totalValidTime_","avgSpeed_");
			
			if ( speed != null && !speed.isInfinite() ) {
				Float maxSpeed = t.getMaxSpeed();
				if (maxSpeed == null || maxSpeed < speed) {
					Toast.makeText(this, "当前最大速度:"+speed, Toast.LENGTH_SHORT).show();
					t.setMaxSpeed(speed);
					dbu.update(t, "maxSpeed_");
				}
			}
			
			if ( loc == null ) {  //开始就结束骑记根本没有定位到
				return ;
			}
			if ( t.getMaxAltitude() == null || loc.getAltitude() > t.getMaxAltitude()) {
				t.setMaxAltitude(loc.getAltitude());
				dbu.update(t, "maxAltitude_");
			}
			
			if ( t.getMinAltitude() == null || loc.getAltitude() > t.getMinAltitude()) {
				t.setMinAltitude(loc.getAltitude());
				dbu.update(t, "minAltitude_");
			}
			
			Float maxGpsSpeed = t.getMaxGpsSpeed();
			if (maxGpsSpeed == null || maxGpsSpeed < loc.getSpeed()) {
				t.setMaxGpsSpeed(loc.getSpeed());
				dbu.update(t, "maxGpsSpeed_");
			}
			
		} catch (DbException e) {
			Toast.makeText(RidingService.this, "更新统计数据失败~_~", Toast.LENGTH_SHORT).show();
			Log.e(TAG, e.getMessage());
		}
	}
	
	private void endTrip(RidingLine t) {
		try {
			t.setIsNow(false);
			t.setEndTime(DateUtils.now());
			
			DbModel dbModel = dbu.findDbModelFirst(Selector.from(LinePoint.class).select("COUNT(id_) AS num,SUM(speed_) AS totalGpsSpeed").where("ridingline_id", "==", t.getId()));
			if (dbModel != null && !dbModel.getDataMap().isEmpty()) {
				int num = dbModel.getInt("num");
				float totalGpsSpeed = 0;
				if ( !dbModel.isEmpty("totalGpsSpeed") ) {
					totalGpsSpeed = dbModel.getFloat("totalGpsSpeed");
				}
				
				float avgGpsSpeed = totalGpsSpeed / num;
				t.setAvgGpsSpeed(avgGpsSpeed);
				dbu.update(t, "isNow_","avgGpsSpeed_","endTime_");
			} else {
				dbu.update(t, "isNow_","endTime_");
			}
			
			statUserData();
			
			// 给DetailActivity发送广播
			Intent intent = new Intent();
 			intent.setAction(RL_UPDATE);
 			intent.putExtra("now_rlId", tNow.getId());
 			intent.putExtra("act", "end");
 			sendBroadcast(intent);
//			statAvgGpsSpeed(t);
 			tNow = null;
			now_rlId = 0;
		} catch (DbException e) {
			Toast.makeText(RidingService.this, "结束骑行记录失败~_~", Toast.LENGTH_SHORT).show();
			Log.e(TAG, e.getMessage());
		}
	}
	
	private boolean statUserData() {
		User user = ((AppContext) getApplication()).loadLoginUser();
		if ( user != null ) {
			try {
				long count = dbu.count(Selector.from(RidingLine.class).where("crudStatus_", "!=", 3));
				if ( count == 0 ) {
					user.setTotalRidingLine(0);
					user.setTotalMileage(0);
					user.setTotalLinePoint(0);
					user.setTotalRidingTime(0);
				} else {
					DbModel dbModel = dbu.findDbModelFirst(Selector.from(RidingLine.class).select("COUNT(id_) AS num,SUM(totalMileage_) AS totalMileage,SUM(totalPoint_) AS totalPoint,SUM(totalTime_) AS totalTime").where("isNow_", "==", 0));
					if (dbModel != null && !dbModel.getDataMap().isEmpty()) {
						int num = dbModel.getInt("num");
						float totalMileage = 0;
						if ( !dbModel.isEmpty("totalMileage") ) {
							totalMileage = dbModel.getFloat("totalMileage");
						}
						int totalPoint = 0;
						if ( !dbModel.isEmpty("totalPoint") ) {
							totalPoint = dbModel.getInt("totalPoint");
						}
						long totalTime = 0;
						if ( !dbModel.isEmpty("totalTime") ) {
							totalTime = dbModel.getInt("totalTime");
						}
						
						user.setTotalRidingLine(num);
						user.setTotalMileage(totalMileage);
						user.setTotalLinePoint(totalPoint);
						user.setTotalRidingTime(totalTime);
					}
				}
				
				((AppContext) getApplication()).updateLoginUser(user);
				return true;
				
			} catch (DbException e) {
				Log.e(TAG, e.getMessage());
				return false;
			}
		}
		return true;
	}
	
	private void startTimer(){
		stopTimer();
		
		mTimer = new Timer();
			mTimerTask = new TimerTask() {
				@Override
				public void run() {

//					totalTime ++;
//					
//					if ( ridingStatus == 2 ) {
//						totalValidTime ++;
//					}
//					
//					Intent intent = new Intent();
//	     			intent.setAction(UPDATE_STAT);
//	     			intent.putExtra("now_rlId", tNow==null?0:tNow.getId());
//	     			intent.putExtra("totalMileage", totalMileage);
//	     			intent.putExtra("distance", (int) distance);
//	     			intent.putExtra("totalPoint", totalPoint);
//	     			intent.putExtra("totalTime", totalTime);
//	     			intent.putExtra("totalValidTime", totalValidTime);
//	     			
//	     			sendBroadcast(intent);
				}
			};

		if ( mTimer != null && mTimerTask != null ) {
			mTimer.schedule(mTimerTask, delay, period);
		}
	}

	private void stopTimer() {
		if (mTimer != null) {
			mTimer.cancel();
			mTimer = null;
		}

		if (mTimerTask != null) {
			mTimerTask.cancel();
			mTimerTask = null;
		}
	}

	public class CrtlReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(RidingService.CTRL_START)) {
				if ( !locClient.isStarted() ) {
					Log.i(TAG, "开始定位!");
					locClient.start();
					// 定位请求
			        int reqType = locClient.requestLocation();
//			        Toast.makeText(RidingService.this, "reqType："+reqType, Toast.LENGTH_SHORT).show();
			        Log.i(TAG, "reqType:"+reqType);
				}
				
				startTrip();
				startTimer();
				isRuning = true;
				
				notification.contentView.setTextViewText(R.id.tvRidingNoticeStatus, "定位中...");
    			notificationManager.notify(NOTIF_RIDING, notification);
			} else if (action.equals(RidingService.CTRL_CONTINUE)) {  //处理详情页的继续通知
				long rlId = intent.getLongExtra("rlId", 0);
				if ( rlId != 0 ) {
					if ( tNow != null && tNow.getId() != null && tNow.getId() != 0) {
						notification.contentView.setTextViewText(R.id.tvRidingNoticeStatus, "有正在进行的骑记...");
		    			notificationManager.notify(NOTIF_RIDING, notification);
						Toast.makeText(RidingService.this, "有正在进行的骑记~_~", Toast.LENGTH_SHORT).show();
					} else {
						try {
							tNow = dbu.findById(RidingLine.class, rlId);
							
							totalMileage = tNow.getTotalMileage();
							totalPoint = tNow.getTotalPoint();
							totalTime = tNow.getTotalTime();
							distance = 0;
							
							now_rlId = tNow.getId();
							
							if ( !locClient.isStarted() ) {
								Log.i(TAG, "开始定位!");
								locClient.start();
								// 定位请求
						        int reqType = locClient.requestLocation();
						        Log.i(TAG, "请求类型:"+reqType);
							}
							
							startTimer();
							isRuning = true;
							
							notification.contentView.setTextViewText(R.id.tvRidingNoticeStatus, "继续骑记...");
			    			notificationManager.notify(NOTIF_RIDING, notification);
						} catch (Exception e) {
							Toast.makeText(RidingService.this, "加载骑记失败~_~", Toast.LENGTH_SHORT).show();
							Log.w(TAG, "查询记录数据异常:", e);
						}
					}
				}
			} else if (action.equals(RidingService.CTRL_STOP)) {
				long rlId = intent.getLongExtra("rlId", 0);
				isRuning = false;
				if ( rlId != 0 ) {  //处理行记详情页的结束通知
					if (tNow != null && tNow.getId() != null 
						&& rlId == tNow.getId().intValue()) {
						if ( locClient.isStarted() ) {
							locClient.stop();
						}
						stopTimer();
						reset(1);
						
						notification.contentView.setTextViewText(R.id.tvRidingNoticeStatus, "未开始...");
		    			notificationManager.notify(NOTIF_RIDING, notification);
					} else {
						return ;
					}
				} else {
					if ( locClient.isStarted() ) {
						locClient.stop();
					}
					stopTimer();
					reset(1);
					notification.contentView.setTextViewText(R.id.tvRidingNoticeStatus, "未开始...");
	    			notificationManager.notify(NOTIF_RIDING, notification);
				}
			} else if (action.equals(RidingService.SYS_EXIT)) {
				isRuning = false;
				if ( locClient.isStarted() ) {
					locClient.stop();
				}
				stopTimer();
				reset(0);
				RidingService.this.stopSelf();
			}
		}
	}
	
	private void registerReceiver() {
		crtlReceiver = new CrtlReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(RidingService.CTRL_START);
		filter.addAction(RidingService.CTRL_PAUSE);
		filter.addAction(RidingService.CTRL_CONTINUE);
		filter.addAction(RidingService.CTRL_STOP);
		filter.addAction(RidingService.SYS_EXIT);
		registerReceiver(crtlReceiver, filter);
		
		alarmReceiver = new AlarmReceiver();
		IntentFilter timerFilter = new IntentFilter();
		timerFilter.addAction(RIDING_TIMER);
		registerReceiver(alarmReceiver, timerFilter);
	}
	
	public class AlarmReceiver extends BroadcastReceiver {  

		@Override
		public void onReceive(Context context, Intent intent) {
			
			if( intent.getAction().equals(RIDING_TIMER) ) {
				if ( isRuning ) {
					totalTime ++;
					
					if ( ridingStatus == 2 ) {
						totalValidTime ++;
					}
					
					Intent intentStat = new Intent();
					intentStat.setAction(UPDATE_STAT);
					intentStat.putExtra("now_rlId", tNow==null?0:tNow.getId());
					intentStat.putExtra("totalMileage", totalMileage);
					intentStat.putExtra("distance", (int) distance);
					intentStat.putExtra("totalPoint", totalPoint);
					intentStat.putExtra("totalTime", totalTime);
					intentStat.putExtra("totalValidTime", totalValidTime);
	     			
	     			sendBroadcast(intentStat);
				}
            }
		}  
	}
	
	
	@Override
	public void onDestroy() {
		this.unregisterReceiver(crtlReceiver);
		this.unregisterReceiver(alarmReceiver);
		// 在服务销毁的时候，使当前服务推出前台，并销毁显示的通知
		stopForeground(false);
		stopTimer();
		
		Intent intent = new Intent();
	    intent.setAction(RIDING_TIMER);
	    PendingIntent sender = PendingIntent.getBroadcast(RidingService.this, 0, intent, 0);
	    
	    final AlarmManager am = (AlarmManager) this.getSystemService(ALARM_SERVICE);
	    am.cancel(sender);
		
		if ( dbu != null) {
			dbu.close();
			dbu = null;
		}
		
		if ( locClient != null) {
			if ( locClient.isStarted() ) {
				locClient.stop();
			}
			locClient = null;
		}
		
		if ( notificationManager != null ) {
			notificationManager.cancelAll();
			notificationManager = null;
		}
		notification = null;
		builder = null;
		
		super.onDestroy();
	}
	
}
